package com.hack4jp.hackearthquakes;

import twitter4j.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class TwitterLogin  extends Activity {
	private final static String 
	CALLBACK_URL  ="com.hack4jp.hackearthquakes://oauth";
	
	TwitterObject twt = null;
	
	protected void onCreate(Bundle bundle) {

		super.onCreate(bundle);
		setContentView(R.layout.twitterlogin);

		twt = new TwitterObject();	
        
		WebView webView = (WebView)findViewById(R.id.twitterlogin);
		WebSettings webSettings = webView.getSettings();

		webSettings.setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient(){
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);

				if(url != null && url.startsWith(CALLBACK_URL)){
					Uri uri = Uri.parse(url);
					int result = Activity.RESULT_OK;
					try {
						twt.parseOAuthParameter(uri);
					} catch (TwitterException e) {
						result = Activity.RESULT_CANCELED;
						e.printStackTrace();
					} catch (Exception e) {
						result = Activity.RESULT_CANCELED;
						e.printStackTrace();
					}

					Intent intent = getIntent();
					setResult(result, intent);
					finish();
				}
			}
		});

		try {
			String url = twt.getAuthorizationURL(CALLBACK_URL);
			webView.loadUrl(url);
		} catch (TwitterException e) {
			int result = Activity.RESULT_CANCELED;
			e.printStackTrace();

			Intent intent = getIntent();
			setResult(result, intent);
			finish();
		}		
	}
}
